﻿/// <reference path="jQuery/jquery.js" />
/// <reference path="jstorage.js" />
/// <reference path="jquery.xdomainajax.js" />


jQuery(document).ready(function () {



	$("a").each(function () { this.onmouseup = this.blur(); });
	//when a hash part of url has changed
	jQuery(window).bind('hashchange', function () {
		showPanel();
	});

	//list all the flashcard from local storage to the list
	listCards();

	//show the list panel
	showPanel();

	//search the word events 
	// click on the button
	jQuery("#searchButton").click(function () {
		searchWord();
	});

	//press enter when inside the input box
	jQuery("#wordToSearch").keypress(function (e) {
		if (e.keyCode == 13) {
			searchWord();
		}
	});

	jQuery(".saveOption").click(function () {
		var id = jQuery(this).closest('.panel').attr('id');
		var input = [];
		jQuery(this).closest('.panel').find('.selection').find("a").each(function (index, element) {
			input.push(element.textContent);
		});

		var $toUpdate = jQuery("#editPanel").find("[data-panel='" + id + "']").closest(".inputItem").find("input");
		//update only if there is some entered text
		if (input.length > 0) {
			$toUpdate.val(input.join(", "));
		}
		window.location.hash = "editPanel";
	});

	setTimeout(function () {
		window.scrollTo(0, 1);
	}, 1000);

});

function deleteAll() {
	var keys = jQuery.jStorage.index();

	for (var key in keys) {
		jQuery.jStorage.deleteKey(keys[key]);
	}

	jQuery.jStorage.flush();
	listCards();
	window.location.hash = "menuPanel";
}

function deleteCard() {
	var key = jQuery("#card").attr("data-key");

	if (key) {
		jQuery.jStorage.deleteKey(key);
		updateListEntry(key);
	}

	window.location.hash = "listPanel";
}

function saveCard() {
	var card = {};

	card["w"] = jQuery("#word").val().trim();
	card["p"] = jQuery("#pronunciation").val().trim();
	card["m"] = jQuery("#meaning").val().trim();
	card["e"] = jQuery("#example").val().trim();
	card["t"] = jQuery("#translation").val().trim();

	var key = jQuery("#card").attr("data-key");

	if (key) {
		jQuery.jStorage.set(key, card);
		updateListEntry(key);
	}
	else {
		if (!isCardAlreadyStored(card)) {
			key = "fc_" + getTimeStamp();
			jQuery.jStorage.set(key, card);
			createListEntry(key);
		}
	}

	jQuery("#card").attr("data-key", "");
	window.location.hash = "listPanel&" + key;
}

function moreOptions(element) {

	var $this = jQuery(element);
	if ($this.hasClass("active")) {
		var panelName = $this.data("panel");

		var $list = jQuery("#" + panelName).find(".options");
		var $selection = jQuery("#" + panelName).find(".selection");
		$selection.text("");

		var currentValue = $this.closest("div").find("input").val();

		var values = currentValue.split(", ");

		for (var value in values) {
			$selection.append(jQuery("<a onclick='removeOption(this)'>").text(values[value]));
			var $item = $list.find("a").filter(function () { return $(this).text() == values[value]; });
			$item.addClass('striked');
		}

		window.location.hash = $this.data("panel");
	}

}

function toggleMoreOption(element) {
	var $item = jQuery(element);

	$item.toggleClass('striked');

	var $selection = $item.closest(".panel").find(".selection")

	if ($item.hasClass("striked")) {
		addTextToSelection($selection, $item.text());
	}
	else {
		removeTextFromSelection($selection, $item.text());
	}

	if ($selection.hasOverflow()) {
		$selection.addClass("red");
	} else {
		$selection.removeClass("red");
	}
}

function changeExample(element) {
	var $item = jQuery(element).find("p");

	jQuery("#example").val($item[0].textContent);
	jQuery("#translation").val($item[1].textContent);

	window.location.hash = "editPanel";
}

function removeOption(element) {

	var $element = jQuery(element);
	var text = $element.text();

	var $options = $element.closest(".panel").find(".options");

	unstrikeTextInOptions($options, text);

	var $selection = $element.closest(".selection");
	$element.remove();

	if ($selection.hasOverflow()) {
		$selection.addClass("red");
	} else {
		$selection.removeClass("red");
	}
}

function removeTextFromSelection($selection, text) {
	var $item = $selection.find("a").filter(function () { return jQuery(this).text() == text; });
	$item.remove();
}

function addTextToSelection($selection, text) {
	if ($selection.find("a").filter(function () { return jQuery(this).text() == text; }).length == 0) {
		$selection.append(jQuery("<a onclick='removeOption(this)'>").text(text));
	}
}

function unstrikeTextInOptions($options, text) {
	var $item = $options.find("a").filter(function () { return jQuery(this).text() == text; });

	if ($item.hasClass("striked")) {
		$item.removeClass("striked");
	}

	if (!$item) {
		queue($options, text);
	}

}

function getTimeStamp() {
	return new Date().getTime();
}

function getHash() {
	return window.location.hash.substring(1).split('&');
}

function showPanel(newPanel) {
	var callback = function () {
	};

	if (!newPanel) {
		var hash = getHash();
		newPanel = hash[0]; //  window.location.hash.substring(1);
	}
	if (!newPanel) {
		return;
	}

	switch (newPanel) {
		case "detail":
			newPanel = "editPanel";
			fillCard(hash[1]);
			if (jQuery("#word").val().length > 0) {
				submitEdit(jQuery("#word").val(), null);
			}
			break;
		case "listPanel":
			clearOptions();
			jQuery("#list").detach().appendTo("#listPanel .content");
			callback = function () {
				if (hash[1]) {
					jQuery(".list a[href$='&" + hash[1] + "']").focus();
				}

			};
			break;
		case "search":
			newPanel = "editPanel";

			if (jQuery("#word").val().length == 0) {

				valueToSearch = decodeURIComponent(hash[1]);
				if (valueToSearch && valueToSearch.length > 0) {
					submitEdit(valueToSearch, null);
				}
			}
			break;
		case "searchPanel":
			clearOptions();
			jQuery("#wordToSearch").val("").focus();
			callback = function () { jQuery("#wordToSearch").focus() };
			break;

		case "deleteListPanel":
			jQuery("#list").detach().appendTo("#deleteListPanel .content");
			break;
		case "learnPanel":
			findRandomCard();
			break;
	}

	jQuery(".panel:visible").hide();
	jQuery("#" + newPanel).show();

	callback();

}

function searchWord() {
	var $searchBox = jQuery("#wordToSearch");

	var word = escape($searchBox.val().trim());
	$searchBox.val("");

	if (word.length > 0) {
		clearCard();
		jQuery("#card").attr("data-key", "");
		jQuery("#update").attr("disabled", "disabled");
		jQuery("#remove").attr("disabled", "disabled");
		jQuery("#save").removeAttr("disabled");



		jQuery("#word").val("");
		window.location.hash = "search&" + word;
	}
	else {
		window.location.hash = "listPanel";
	}
}


function clearCard() {
	jQuery("#word").val("");
	jQuery("#pronunciation").val("");
	jQuery("#example").val("");
	jQuery("#meaning").val("");
	jQuery("#translation").val("");

	jQuery("#editPanel .cardAction").hide();


	clearOptions();
}

function clearOptions() {
	jQuery("#words").empty();
	jQuery("#pronunciations").empty();
	jQuery("#meanings").empty();
	jQuery("#examples").empty();

	jQuery("#editPanel").find(".moreOptions").removeClass("active");

}

function submitEdit(value, settings) {

	var callbacks = $.Callbacks();

	value = encodeURIComponent(jQuery.trim(value));
	searchWordreference(value, callbacks);
	searchOxford(value);
	searchSlovnikOnLine(value);
	searchPronunciation(value);


	return value;
}




jQuery.fn.HasScrollBar = function () {

	var _hasScrollBar = false;
	if ((this.clientHeight < this.scrollHeight) || (this.clientWidth < this.scrollWidth)) {
		_hasScrollBar = true;
	}
	return _hasScrollBar;
}

jQuery.fn.justtext = function () {

	return $(this).clone()
			.children()
			.remove()
			.end()
			.text().trim();

}

function parse($text) {
	$parsedText = str_replace(chr(10), "", $text);
	return str_replace(chr(13), "", $parsedText);

}

jQuery.fn.hasOverflow = function () {
	var $this = $(this);
	var $children = $this.find('*');
	var len = $children.length;

	if (len) {
		var maxWidth = 0;
		var maxHeight = 0
		$children.map(function () {
			maxWidth += $(this).outerWidth(true);
			maxHeight = Math.max(maxHeight, $(this).outerHeight(true));
		});

		return maxWidth > $this.width() || maxHeight > $this.height();
	}

	return false;
};

function listCards() {

	jQuery("#flashcardList").children().remove();

	var keys = jQuery.jStorage.index();
	keys.sort(sortCards);
	for (var key in keys) {
		var realKey = keys[key];
		if (realKey.indexOf("fc_") == 0) {

			if (jQuery("#cards").find("[value='" + realKey + "']").length == 0) {
				createListEntry(realKey);
			}
		}
	}
}

function sortCards(x, y) {
	var xValue = jQuery.jStorage.get(x);
	var yValue = jQuery.jStorage.get(y);

	return xValue["w"].localeCompare(yValue["w"]);
}

function isCardAlreadyStored(card) {
	var keys = jQuery.jStorage.index();

	for (var key in keys) {
		var realKey = keys[key];
		if (realKey.indexOf("fc_") == 0) {
			var existingCard = jQuery.jStorage.get(realKey);
			if (existingCard["w"] == card["w"]
				&& existingCard["p"] == card["p"]
				&& existingCard["e"] == card["e"]
				&& existingCard["m"] == card["m"]
				&& existingCard["t"] == card["t"])
				return true;
		}
	}

	return false;
}

function updateListEntry(key) {
	var card = jQuery.jStorage.get(key);
	var $item = jQuery("#flashcardList a[href$='&" + key + "']");

	if (card) {


		$item.find(".word").text(card["w"]);
		$item.find(".meaning").text(card["m"]);
		$item.find(".pronunciation").text(card["p"]);
		$item.find(".example").text(card["e"]);
		$item.find(".translation").text(card["t"]);
	}
	else {
		$item.closest("li").remove();
	}
}


function createListEntry(key) {
	var card = jQuery.jStorage.get(key)


	var li = jQuery("<li>");
	var item = jQuery("<a ondblclick='alert();'>").attr("href", "#detail&" + key).addClass("art");
	li.append(item);
	var content = jQuery("<div class='card'>").data("key", key).appendTo(item);

	jQuery("<div class='word'>").text(card["w"]).appendTo(content);
	jQuery("<div class='meaning'>").text(card["m"]).appendTo(content);
	jQuery("<div class='pronunciation'>").text(card["p"]).appendTo(content);
	jQuery("<div class='example'>").text(card["e"]).appendTo(content);
	jQuery("<div class='translation'>").text(card["t"]).appendTo(content);

	jQuery("#flashcardList").append(li);
}


function fillCard(key) {
	var card = jQuery.jStorage.get(key);

	jQuery("#card").attr("data-key", key);
	jQuery("#word").val(card["w"]);
	jQuery("#pronunciation").val(card["p"]);
	jQuery("#meaning").val(card["m"]);
	jQuery("#example").val(card["e"]);
	jQuery("#translation").val(card["t"]);

	jQuery("#editPanel .cardAction").show();
}

var cards;

function switchOrder() {
	var $order = jQuery("#learnOrder");
	if ($order.hasClass("icon-star")) {
		$order.removeClass("icon-star");
		$order.addClass("icon-star-empty");
	}
	else {
		$order.removeClass("icon-star-empty");
		$order.addClass("icon-star");
	}

	if (jQuery("#learnOrder").hasClass("icon-star-empty")) {
		jQuery(".learnCard .word").hide();
		jQuery(".learnCard .meaning").show();
	}
	else {
		jQuery(".learnCard .word").show();
		jQuery(".learnCard .meaning").hide();
	}
}
function findRandomCard() {
	var $question = jQuery(".learnCard .word");
	var $answer = jQuery(".learnCard .meaning"); ;

	if (jQuery("#learnOrder").hasClass("icon-star-empty")) {
		$question = jQuery(".learnCard .meaning");
		$answer = jQuery(".learnCard .word")
	}

	if ($question.text().length == 0) {
		fillRandom();
	}
	else {
		if ($answer.is(":visible")) {
			fillRandom();
		}
		else {
			$answer.show();
		}
	}
}

function fillRandom() {
	if (!cards || cards.length == 0) {
		cards = jQuery.jStorage.index();
	}

	var index = Math.ceil(Math.random() * (cards.length - 1));
	var card = jQuery.jStorage.get(cards[index]);

	cards.splice(index, 1);

	jQuery(".learnCard .word").text(card["w"]);
	jQuery(".learnCard .meaning").text(card["m"]).hide();

	if (jQuery("#learnOrder").hasClass("icon-star-empty")) {
		jQuery(".learnCard .word").hide();
		jQuery(".learnCard .meaning").show();
	}
}

function uploadJsonP(address) {
	$.getJSON(address + "?jsoncallback=?", function (data) {
		alert('aaa');
	});


}

function jsonpCallback(data) {
	var card = {};

	for (i = 0; i < data.length; i++) {


		card["w"] = data[i][0];
		card["p"] = data[i][1];
		card["m"] = data[i][2];
		card["e"] = data[i][3];
		card["t"] = data[i][4];

		if (!isCardAlreadyStored(card)) {
			key = "fc_" + getTimeStamp();
			jQuery.jStorage.set(key, card);
			createListEntry(key);
		}
	}

	window.location.hash = "listPanel&" + key;
}